package com.googlecode.moneyManager.model;

import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DateFormat;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Transient;

import org.apache.log4j.*;

@Entity
public class Replenish extends BaseEntity{

    private static org.apache.log4j.Logger log = Logger.getLogger(Replenish.class);

    private long addingDate;

    private Amount amount;

    private Deposit deposit;
    
    public Replenish(){}

    public long getAddingDate() {
        return addingDate;
    }

    public void setAddingDate(long addingDate) {
        this.addingDate = addingDate;
    }
    
    @OneToOne
    @PrimaryKeyJoinColumn
    public Amount getAmount() {
        return amount;
    }

    public void setAmount(Amount amount) {
        this.amount = amount;
    }
    @ManyToOne(cascade = CascadeType.ALL)
    public Deposit getDeposit() {
        return deposit;
    }

    public void setDeposit(Deposit deposit) {
        this.deposit = deposit;
    }

    /**
     * calculate profit from layoutdate to toDate
     * 
     * @param toDate
     * @return Amount
     */
    @Transient
    Amount getProfitAmount(final long toDate) {
        long daysFromMilis = 24 * 60 * 60 * 1000;
        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
        Date d = new Date();
        d.setTime(addingDate);
        long depositPeriod = deposit.getExpiredDate() - deposit.layoutDate;
        long profitPeriod = toDate - addingDate;
        BigDecimal profitPercentDecimal = deposit.getPercent().getNumberOfPercent().multiply(new BigDecimal(profitPeriod + ""));
        profitPercentDecimal = profitPercentDecimal.divide(new BigDecimal(depositPeriod + ""),new MathContext(100));
        log.debug(profitPercentDecimal);
        BigDecimal profitAmountSum = amount.getAmount().multiply(profitPercentDecimal,new MathContext(100));
        log.debug("profitPercen = " + profitAmountSum);
        Amount prAmount = new Amount(profitAmountSum, amount.getCurrency());
        log.debug("profitPercen = " + prAmount);
        return prAmount;
    }
}
